package cn.itsource.system.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.system.domain.Menu;
import cn.itsource.system.mapper.MenuMapper;
import cn.itsource.system.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> menuTree() {
        //1.将所有菜单装到Map中 - 当做缓存，通过id找到找到当前菜单
        List<Menu> menus = menuMapper.findAll();
        Map<Long,Menu> map =  new HashMap<>();
        for (Menu menu : menus) {
            map.put(menu.getId(),menu);
        }
        List<Menu> menuTree = new ArrayList<>();
        for (Menu menu : menus) {
            if(menu.getParentId() == null){
                menuTree.add(menu);
            }else{
                //当前菜单的父id
                Long parentId = menu.getParentId();
                //找到父对象
                Menu parentMenu = map.get(parentId);
                if(parentMenu!=null){
                    //将自己装到父菜单的集合中
                    parentMenu.getChildren().add(menu);
                }
            }
        }
        return menuTree;
    }
}
